// 全局搜索工具类
const MockData = require('./mockData.js')

/**
 * 全局搜索工具
 * 支持搜索课程、穴位、反射区、商品等多种内容类型
 */
const SearchUtil = {
  
  /**
   * 执行全局搜索
   * @param {string} keyword 搜索关键词
   * @param {object} options 搜索选项 {types: ['course', 'acupoint', 'reflex', 'product'], limit: 10}
   * @returns {object} 搜索结果 {courses: [], acupoints: [], reflexZones: [], products: [], total: 0}
   */
  globalSearch(keyword, options = {}) {
    if (!keyword || keyword.trim() === '') {
      return {
        courses: [],
        acupoints: [],
        reflexZones: [],
        products: [],
        total: 0
      }
    }

    const searchKeyword = keyword.trim().toLowerCase()
    const types = options.types || ['course', 'acupoint', 'reflex', 'product']
    const limit = options.limit || 20 // 每种类型的最大结果数
    
    let results = {
      courses: [],
      acupoints: [],
      reflexZones: [],
      products: [],
      total: 0
    }

    // 搜索课程
    if (types.includes('course')) {
      results.courses = this.searchCourses(searchKeyword, limit)
    }

    // 搜索穴位
    if (types.includes('acupoint')) {
      results.acupoints = this.searchAcupoints(searchKeyword, limit)
    }

    // 搜索反射区
    if (types.includes('reflex')) {
      results.reflexZones = this.searchReflexZones(searchKeyword, limit)
    }

    // 搜索商品
    if (types.includes('product')) {
      results.products = this.searchProducts(searchKeyword, limit)
    }

    // 计算总数
    results.total = results.courses.length + results.acupoints.length + 
                   results.reflexZones.length + results.products.length

    return results
  },

  /**
   * 搜索课程
   * @param {string} keyword 搜索关键词
   * @param {number} limit 结果数量限制
   * @returns {array} 课程列表
   */
  searchCourses(keyword, limit = 20) {
    const courses = MockData.courses || []
    
    return courses.filter(course => {
      // 搜索标题、简介、详情
      const matchTitle = course.title && course.title.toLowerCase().includes(keyword)
      const matchIntro = course.intro && course.intro.toLowerCase().includes(keyword)
      const matchDetail = course.detail && course.detail.toLowerCase().includes(keyword)
      const matchType = course.typeText && course.typeText.toLowerCase().includes(keyword)
      
      return matchTitle || matchIntro || matchDetail || matchType
    }).slice(0, limit).map(course => ({
      ...course,
      type: 'course',
      searchType: '课程'
    }))
  },

  /**
   * 搜索穴位
   * @param {string} keyword 搜索关键词
   * @param {number} limit 结果数量限制
   * @returns {array} 穴位列表
   */
  searchAcupoints(keyword, limit = 20) {
    const acupoints = MockData.acupoints || []
    
    return acupoints.filter(acupoint => {
      // 搜索穴位名称、位置、描述
      const matchTitle = acupoint.imageTitle && acupoint.imageTitle.toLowerCase().includes(keyword)
      const matchCategory = acupoint.categoryText && acupoint.categoryText.toLowerCase().includes(keyword)
      const matchPosition = acupoint.bodyPosition && acupoint.bodyPosition.toLowerCase().includes(keyword)
      const matchDesc = acupoint.description && acupoint.description.toLowerCase().includes(keyword)
      
      return matchTitle || matchCategory || matchPosition || matchDesc
    }).slice(0, limit).map(acupoint => ({
      ...acupoint,
      type: 'acupoint',
      searchType: '穴位'
    }))
  },

  /**
   * 搜索反射区
   * @param {string} keyword 搜索关键词
   * @param {number} limit 结果数量限制
   * @returns {array} 反射区列表
   */
  searchReflexZones(keyword, limit = 20) {
    const reflexZones = MockData.reflexZones || []
    
    return reflexZones.filter(zone => {
      // 搜索反射区名称、位置、功能、操作方法
      const matchName = zone.name && zone.name.toLowerCase().includes(keyword)
      const matchPosition = zone.positionText && zone.positionText.toLowerCase().includes(keyword)
      const matchLocation = zone.location && zone.location.toLowerCase().includes(keyword)
      const matchFunction = zone.function && zone.function.toLowerCase().includes(keyword)
      const matchOperation = zone.operation && zone.operation.toLowerCase().includes(keyword)
      
      return matchName || matchPosition || matchLocation || matchFunction || matchOperation
    }).slice(0, limit).map(zone => ({
      ...zone,
      type: 'reflex',
      searchType: '反射区'
    }))
  },

  /**
   * 搜索商品
   * @param {string} keyword 搜索关键词
   * @param {number} limit 结果数量限制
   * @returns {array} 商品列表
   */
  searchProducts(keyword, limit = 20) {
    const products = MockData.products || []
    
    return products.filter(product => {
      // 搜索商品名称、简介、详情
      const matchName = product.name && product.name.toLowerCase().includes(keyword)
      const matchIntro = product.intro && product.intro.toLowerCase().includes(keyword)
      const matchDetail = product.detail && product.detail.toLowerCase().includes(keyword)
      
      return matchName || matchIntro || matchDetail
    }).slice(0, limit).map(product => ({
      ...product,
      type: 'product',
      searchType: '商品'
    }))
  },

  /**
   * 获取搜索建议
   * @param {string} keyword 搜索关键词
   * @param {number} limit 建议数量限制
   * @returns {array} 搜索建议列表
   */
  getSearchSuggestions(keyword, limit = 10) {
    if (!keyword || keyword.trim() === '') {
      return []
    }

    const searchKeyword = keyword.trim().toLowerCase()
    const suggestions = []
    
    // 从课程标题中提取建议
    const courses = MockData.courses || []
    courses.forEach(course => {
      if (course.title && course.title.toLowerCase().includes(searchKeyword)) {
        suggestions.push({
          text: course.title,
          type: 'course'
        })
      }
    })

    // 从穴位名称中提取建议
    const acupoints = MockData.acupoints || []
    acupoints.forEach(acupoint => {
      if (acupoint.imageTitle && acupoint.imageTitle.toLowerCase().includes(searchKeyword)) {
        suggestions.push({
          text: acupoint.imageTitle,
          type: 'acupoint'
        })
      }
    })

    // 从反射区名称中提取建议
    const reflexZones = MockData.reflexZones || []
    reflexZones.forEach(zone => {
      if (zone.name && zone.name.toLowerCase().includes(searchKeyword)) {
        suggestions.push({
          text: zone.name,
          type: 'reflex'
        })
      }
    })

    // 去重并限制数量
    const uniqueSuggestions = []
    const textSet = new Set()
    
    for (const suggestion of suggestions) {
      if (!textSet.has(suggestion.text)) {
        textSet.add(suggestion.text)
        uniqueSuggestions.push(suggestion)
        if (uniqueSuggestions.length >= limit) {
          break
        }
      }
    }

    return uniqueSuggestions
  },

  /**
   * 合并搜索结果为单一列表
   * @param {object} results 搜索结果对象
   * @returns {array} 合并后的结果列表
   */
  mergeResults(results) {
    const merged = []
    
    // 添加课程结果
    if (results.courses && results.courses.length > 0) {
      merged.push(...results.courses)
    }
    
    // 添加穴位结果
    if (results.acupoints && results.acupoints.length > 0) {
      merged.push(...results.acupoints)
    }
    
    // 添加反射区结果
    if (results.reflexZones && results.reflexZones.length > 0) {
      merged.push(...results.reflexZones)
    }
    
    // 添加商品结果
    if (results.products && results.products.length > 0) {
      merged.push(...results.products)
    }
    
    return merged
  },

  /**
   * 格式化搜索结果用于显示
   * @param {object} item 搜索结果项
   * @returns {object} 格式化后的结果
   */
  formatResult(item) {
    const formatted = {
      id: item.id,
      type: item.type,
      searchType: item.searchType,
      title: '',
      description: '',
      image: '',
      tags: []
    }

    switch (item.type) {
      case 'course':
        formatted.title = item.title
        formatted.description = item.intro || item.detail || ''
        formatted.image = item.cover
        formatted.tags = [item.typeText, item.isFree ? '免费' : `¥${item.price}`]
        if (item.viewCount) {
          formatted.tags.push(`${item.viewCount}人学习`)
        }
        break
        
      case 'acupoint':
        formatted.title = item.imageTitle
        formatted.description = item.description || ''
        formatted.image = item.thumbnailUrl || item.imageUrl
        formatted.tags = [item.categoryText, item.bodyPosition]
        if (item.isFree) {
          formatted.tags.push('免费')
        } else {
          formatted.tags.push(`¥${item.price}`)
        }
        break
        
      case 'reflex':
        formatted.title = item.name
        formatted.description = item.function || ''
        formatted.image = item.images
        formatted.tags = [item.positionText, item.isFree ? '免费' : `¥${item.price}`]
        break
        
      case 'product':
        formatted.title = item.name
        formatted.description = item.intro || ''
        formatted.image = item.cover
        formatted.tags = [`¥${item.price}`]
        if (item.sales) {
          formatted.tags.push(`已售${item.sales}`)
        }
        break
    }

    return formatted
  }
}

module.exports = SearchUtil

